package com.spring.cloud.alibaba.service.provider.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spring.cloud.alibaba.commons.params.StockParam;
import com.spring.cloud.alibaba.commons.pojo.ResponseVo;
import com.spring.cloud.alibaba.commons.pojo.StockInfo;
import com.spring.cloud.alibaba.service.provider.mapper.StockMapper;
import com.spring.cloud.alibaba.service.provider.service.IStockService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class StockService extends ServiceImpl<StockMapper, StockInfo> implements IStockService {

    private static final String DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";

    @Override
    public ResponseVo findStockByGoodCode(String goodCode) {
        log.info("goodCode={}", goodCode);
        QueryWrapper<StockInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("good_code", goodCode);
        StockInfo stockInfo = this.baseMapper.selectOne(queryWrapper);
        ResponseVo responseVo = ResponseVo.success(stockInfo);
        return responseVo;
    }

    @Override
    public ResponseVo updateStockById(StockInfo stockInfo) {
        log.info("id={}, count={}", stockInfo.getId(), stockInfo.getCount());
        if (StringUtils.isEmpty(stockInfo.getLastUpdatedBy())) {
            stockInfo.setLastUpdatedBy("system");
            stockInfo.setLastUpdatedDate(new Date(System.currentTimeMillis()));
        }
        Integer updateCount = this.baseMapper.updateById(stockInfo);
        ResponseVo responseVo = ResponseVo.success(updateCount);
        return responseVo;
    }

    @Override
    public ResponseVo saveOne(StockInfo stockInfo) {
        log.info("stockInfo={}", JSONUtil.toJsonStr(stockInfo));
        setCreatedByAndUpdatedBy(stockInfo);
        setCreatedByDateAndUpdatedDate(stockInfo);
        int result = this.baseMapper.insert(stockInfo);
        ResponseVo responseVo;
        if (result == 1) {
            responseVo = ResponseVo.success(result);
        } else {
            responseVo = ResponseVo.error("添加库存数据失败");
        }
        return responseVo;
    }

    @Override
    public ResponseVo saveBatch(List<StockInfo> stockInfoEntityList) {
        log.info("stockInfoEntityList={}", JSONUtil.toJsonStr(stockInfoEntityList));
        stockInfoEntityList.forEach(item -> {
            setCreatedByAndUpdatedBy(item);
            setCreatedByDateAndUpdatedDate(item);
        });
        boolean result = this.saveBatch(stockInfoEntityList, 500);
        ResponseVo responseVo;
        if (result) {
            responseVo = ResponseVo.success(result);
        } else {
            responseVo = ResponseVo.error("添加库存数据失败");
        }
        return responseVo;
    }

    @Override
    public ResponseVo queryListByCondition(StockParam stockParam) {
        log.info("stockParam={}", stockParam);
        QueryWrapper<StockInfo> queryWrapper = getQueryWrapperByParam(stockParam);
        List<StockInfo> stockInfoEntityList = super.list(queryWrapper);
        log.info("stockInfoEntityList", JSONUtil.toJsonStr(stockInfoEntityList));
        ResponseVo responseVo = ResponseVo.success(stockInfoEntityList);
        return responseVo;
    }

    @Override
    public ResponseVo queryPageDataByCondition(int pageNo, int pageSize, StockParam stockParam) {
        log.info("pageNo={},pageSize={},stockParam={}", pageNo, pageSize, stockParam);
        Page<StockInfo> pageParam = new Page<>(pageNo, pageSize);
        QueryWrapper<StockInfo> queryWrapper = getQueryWrapperByParam(stockParam);
        IPage<StockInfo> pageData = super.page(pageParam, queryWrapper);
        ResponseVo responseVo = ResponseVo.success(pageData);
        return responseVo;
    }

    private void setCreatedByAndUpdatedBy(StockInfo stockInfo) {
        if (StringUtils.isEmpty(stockInfo.getCreatedBy())){
            stockInfo.setCreatedBy("system");
        }
        if (StringUtils.isEmpty(stockInfo.getLastUpdatedBy())){
            stockInfo.setLastUpdatedBy("system");
        }
    }

    private void setCreatedByDateAndUpdatedDate(StockInfo stockInfo) {
        if (stockInfo.getCreatedDate() == null) {
            stockInfo.setCreatedDate(DateUtil.date(System.currentTimeMillis()));
        }
        if (stockInfo.getLastUpdatedDate() == null) {
            stockInfo.setLastUpdatedDate(DateUtil.date(System.currentTimeMillis()));
        }
    }

    private QueryWrapper<StockInfo> getQueryWrapperByParam(StockParam stockParam) {
        QueryWrapper<StockInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("id", "good_code", "good_name", "unit_price", "count",
                "created_date", "created_by", "last_updated_by", "last_updated_date");
        // 注意加了唯一索引的列使用like查询会导致查不出结果
        queryWrapper.eq(!StringUtils.isEmpty(stockParam.getGoodCode()), "good_code", stockParam.getGoodCode());

        queryWrapper.likeRight(!StringUtils.isEmpty(stockParam.getGoodName()), "good_name", stockParam.getGoodName());

        queryWrapper.eq(stockParam.getCount() != null, "count", stockParam.getCount());

        queryWrapper.ge(stockParam.getQueryMinUnitPrice() != null,"unit_price", stockParam.getQueryMinUnitPrice());

        queryWrapper.le(stockParam.getQueryMaxUnitPrice() != null,"unit_price", stockParam.getQueryMaxUnitPrice());

        queryWrapper.eq(StringUtils.isNotBlank(stockParam.getCreatedBy()), "created_by", stockParam.getCreatedBy());

        if (!StringUtils.isEmpty(stockParam.getQueryMinCreatedDate())) {
            DateTime queryMinCreatedDate = DateUtil.parse(stockParam.getQueryMinCreatedDate(), DATE_TIME_FORMAT);
            queryWrapper.ge("created_date", queryMinCreatedDate);
        }
        if (!StringUtils.isEmpty(stockParam.getQueryMaxCreatedDate())) {
            DateTime queryMaxCreatedDate = DateUtil.parse(stockParam.getQueryMaxCreatedDate(), DATE_TIME_FORMAT);
            queryWrapper.le("created_date", queryMaxCreatedDate);
        }
        if (!StringUtils.isEmpty(stockParam.getLastUpdatedBy())) {
            queryWrapper.eq(StringUtils.isNotBlank(stockParam.getLastUpdatedBy()), "last_updated_by", stockParam.getLastUpdatedBy());
        }
        if (!StringUtils.isEmpty(stockParam.getQueryMinUpdateDate())) {
            DateTime queryMinUpdateDate = DateUtil.parse(stockParam.getQueryMinUpdateDate(), DATE_TIME_FORMAT);
            queryWrapper.ge("last_updated_date", queryMinUpdateDate);
        }
        if (!StringUtils.isEmpty(stockParam.getQueryMaxUpdateDate())) {
            DateTime queryMaxUpdateDate = DateUtil.parse(stockParam.getQueryMaxUpdateDate(), DATE_TIME_FORMAT);
            queryWrapper.le("last_updated_date", queryMaxUpdateDate);
        }
        queryWrapper.orderByAsc("id");
        return queryWrapper;
    }
}
